const mysql = require('mysql');

let sqlInfo = {
  connectionLimit: 100,
  host: 'localhost',
  user: 'root',
  prot: 3306,
  password: '123456',
  database: 'mydb',
};

let pool = mysql.createPool(sqlInfo);

let connect = () => {
  return new Promise((resolve, reject) => {
    pool.getConnection((err, connection) => {
      !err ? resolve(connection) : reject(err);
    });
  });
};
// 单数据查询
let find = (table, params) => {
  return new Promise(async (resolve, reject) => {
    let connection = await connect();
    connection.query(
      `SELECT * FROM ${table} ${params ? 'where ?' : ''}`,
      [{ ...params }],
      (err, res) => {
        !err ? resolve(res) : reject(err);
        connection.release();
      }
    );
  });
};

// 登录
let login = (params) => {
  return new Promise(async (resolve, reject) => {
    let connection = await connect();
    connection.query(
      `SELECT * FROM user WHERE user= ? && psd= ? `,
      params,
      (err, res) => {
        !err ? resolve(res) : reject(err);
        connection.release();
      }
    );
  });
};

// 插入
let insert = (table, params) => {
  return new Promise(async (resolve, reject) => {
    let connection = await connect();
    let sql = `INSERT INTO ${table} SET ?`;

    connection.query(sql, [params], (err, results, fields) => {
      !err ? resolve(results) : reject('inter error:' + err);
      connection.release();
    });
  });
};
// 删除某行数据,单个
let del = (table, params) => {
  return new Promise(async (resolve, reject) => {
    let connection = await connect();
    connection.query(
      `DELETE FROM ${table} WHERE ?`,
      [
        {
          ...(params ? params : ''),
        },
      ],
      (err, results, fields) => {
        !err ? resolve(results) : reject(err);
        connection.release();
      }
    );
  });
};

// 删除整个表
let clearSql = (table) => {
  return new Promise(async (resolve, reject) => {
    let connection = await connect();
    connection.query(`DELETE FROM ${table} `, (err, results, fields) => {
      !err ? resolve(results) : reject(err);
      connection.release();
    });
  });
};
// 更新表
let update = (table, params1, params2) => {
  return new Promise(async (resolve, reject) => {
    let connection = await connect();
    connection.query(
      `UPDATE ${table} SET ? WHERE ?`,
      [
        {
          ...(params1 ? params1 : ''),
        },
        {
          ...(params2 ? params2 : ''),
        },
      ],
      (err, results, fields) => {
        !err ? resolve(results) : reject(err);
        connection.release();
      }
    );
  });
};

module.exports = {
  connect,
  find,
  insert,
  del,
  clearSql,
  update,
  login,
};
